package com.ego.admin.controller;

import com.ego.admin.oauth.OauthToken;
import com.ego.admin.po.SysAdmin;
import com.ego.admin.service.SysLoginLogService;
import com.ego.admin.service.SysAdminService;
import com.ego.admin.service.SysAdminTokenService;
import com.ego.admin.service.SysCaptchaService;
import com.ego.admin.vo.SysLoginVo;
import com.ego.common.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;


/**
 * @program: ego
 * @description:
 * @author: KamTang
 * @create: 2022-11-11 11:17
 **/
@RestController
@RequestMapping("/sys")
@Slf4j
public class SysLoginController extends Administrator {
    @Autowired
    private SysAdminService sysAdminService;
    @Autowired
    private SysAdminTokenService sysAdminTokenService;
    @Autowired
    private SysCaptchaService sysCaptchaService;
    @Autowired
    private SysLoginLogService loginLogService;

    @GetMapping("/captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        // 获取图片验证码
        BufferedImage image = sysCaptchaService.get(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    @PostMapping("/login")
    public Result login(@RequestBody SysLoginVo sysLoginVo, HttpServletRequest request) throws UnsupportedEncodingException {
        boolean captcha = sysCaptchaService.validate(sysLoginVo.getUuid(), sysLoginVo.getCaptcha());
        if (!captcha) {
            return Result.error("验证码不正确");
        }
        // 用户信息
        SysAdmin admin = sysAdminService.queryByUserName(sysLoginVo.getUsername());
        log.error("admin => {}", admin);
        // 账号不存在、密码错误
        if (admin == null || !admin.getPassword().equals(new Sha256Hash(sysLoginVo.getPassword(), admin.getSalt()).toHex())) {
            return Result.error("账号或密码不正确");
        }

        // 账号锁定
        if (admin.getStatus() == 0) {
            return Result.error("该账号已被锁定,请联系管理员");
        }
        // TODO 权限。。。
        Result result = sysAdminTokenService.createToken(admin.getUserId());
        String token = (String) result.get("token");
        log.info("token => {}", token);
        OauthToken oauthToken = new OauthToken(token);
        SecurityUtils.getSubject().login(oauthToken);
        // 保存登录日志
        loginLogService.addLoginReport(request);

        return result.put("admin", admin);
    }

    @PostMapping("/logout")
    public Result logout() {
        sysAdminTokenService.logout(getAdmin().getUserId());
        return Result.ok();
    }
}
